package cn.tom.controller;

import cn.tom.tools.XResp;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;


@ControllerAdvice
@Slf4j
@Controller
public class ErrController {
    @ExceptionHandler(IOException.class)
    public void IOException(IOException e , HttpServletResponse response)throws Exception{
        log.error(e.getMessage());
        response.setStatus(500);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(XResp.packJson(500,"",""));
        response.flushBuffer();
    }

    @ExceptionHandler(NullPointerException.class)
    public void NullPointerException(NullPointerException e , HttpServletResponse response)throws Exception{
        log.error(e.getMessage());
        response.setStatus(500);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(XResp.packJson(500,"空指针异常",""));
        response.flushBuffer();
    }

    @ExceptionHandler(SQLException.class)
    public void handerSQL( SQLException e , HttpServletResponse response)throws Exception{
        log.info(e.getMessage());
        response.setStatus(500);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(XResp.packJson(500,"SQL有误",""));
        response.flushBuffer();
        //XJson code msg data
    }

    @ExceptionHandler(Exception.class)
    public void handerExc( Exception e , HttpServletResponse response){
        try{
            log.error(e.getMessage());
            response.setStatus(500);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.getWriter().println(XResp.packJson(500,"系统异常",""));
            response.flushBuffer();
        }catch (Exception ex){

        }
    }
}
